from django.db import models


# Create your models here.
class obs_project(models.Model):
    project_id = models.BigAutoField(primary_key=True)
    project_name = models.CharField(max_length=100)

    # project_build_results

    def __str__(self):
        return self.project_name


class obs_package(models.Model):
    project = models.ForeignKey(obs_project, on_delete=models.CASCADE)
    updated_at = models.DateTimeField(auto_now=True)
    package_name = models.CharField(max_length=100)
    package_href = models.CharField(max_length=100, null=True)
    package_changed = models.CharField(max_length=100)

    def __str__(self):
        return f'{self.project.project_name} - {self.package_name}'

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['project', 'package_name'],
                                    name='unique_package')
        ]
        unique_together = ['project', 'package_name']


class obs_package_build_log(models.Model):
    project = models.ForeignKey(obs_project, on_delete=models.CASCADE)
    package = models.ForeignKey(obs_package, on_delete=models.CASCADE)
    build_time = models.DateTimeField(null=True)
    fetch_time = models.DateTimeField(null=True)
    build_log_id = models.CharField(max_length=100, null=True, unique=True)
    status = models.CharField(max_length=100, null=True)

    def __str__(self):
        return f'{self.package} - {str(self.fetch_time)}'


class obs_job_history(models.Model):
    project = models.ForeignKey(obs_project, on_delete=models.CASCADE)
    package = models.ForeignKey(obs_package, on_delete=models.CASCADE)
    package_revision = models.IntegerField()
    build_time = models.IntegerField()
    build_reason = models.CharField(max_length=100)
    build_status_code = models.CharField(max_length=100)
    build_duration = models.IntegerField()
    build_worker = models.CharField(max_length=100)
    versrel = models.CharField(max_length=50)
    srcmd5 = models.CharField(max_length=50)
    mongo_log_id = models.CharField(max_length=100, null=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['project', 'package', 'build_time'],
                                    name='unique_build_time')
        ]
        unique_together = ['project', 'package', 'build_time']

    def __str__(self):
        return f'{self.package} - {self.build_time}'


class obs_revision(models.Model):
    project = models.ForeignKey(obs_project, on_delete=models.CASCADE)
    package = models.ForeignKey(obs_package, on_delete=models.CASCADE)
    revision_id = models.IntegerField()
    commit_user = models.CharField(max_length=100)
    commit_time = models.DateTimeField(null=True)
    commit_unix_time = models.IntegerField(null=True)
    comment = models.TextField(null=True)

    # files_changed
    # source

    def __str__(self):
        return f'{self.package} - rev {self.revision_id}'
